package com.lxw.camera.ui.activity

import android.app.Activity
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.SurfaceView
import android.widget.Button
import com.lxw.camera.R
import com.lxw.camera.presenter.MainPresenter
import com.lxw.camera.ui.view.IMainView
import java.io.File

/**
 * 猿代码： Lxw
 * Email: China2021@126.com
 * 时间轴： 2018年 03月 08 日 下午5:25
 */
class MainActivity : BaseActivity<MainActivity, MainPresenter>(), IMainView {
    override fun getPicFile(): File? {
        return null
    }


    private val TAG = "MainActivity"
    private var btMain: Button? = null
    private var sv: SurfaceView? = null
    private var mFile: File? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        btMain?.setOnClickListener {
            mPresenter?.openCamera(this, this)
        }


    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>?, grantResults: IntArray?) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == MainPresenter.OPEN_CAMERA) {
            if (permissions != null) {
                for (i in permissions.indices) {
                    if (grantResults != null) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            showToastMessage("${permissions[i]}，授权成功(${grantResults[i]})！")
                            mPresenter?.openCamera(this, this)
                        } else {
                            showToastMessage("$permissions[i]，授权失败(${grantResults[i]})!")
                        }
                    }
                }
            }
        }
    }

    /**
     * 逻辑层会回调到这里让界面处理
     */
    override fun showMainButton(result: Boolean) {
        Log.d(TAG, "密码：${if (result) "Success" else "Error"}")
    }


    /**
     * 提供布局ID
     */
    override fun contentId(): Int {
        return R.layout.activity_main
    }

    /**
     * 提供Presenter
     */
    override fun createPresenter(): MainPresenter {
        return MainPresenter()
    }

    override fun getSurfaceView(): SurfaceView? {
        return sv
    }

    /**
     * 不使用框架，自己手动初始化View,所以主动覆盖基类方法。
     */
    override fun initView() {
        btMain = findViewById(R.id.bt_main)
        sv = findViewById(R.id.sv)
    }

    /**
     * 释放资源
     */
    override fun onDestroy() {
        super.onDestroy()
        mPresenter?.releaseCameraDevice()
    }


    override fun getActivity(): Activity {
        return this
    }

    override fun onStart() {
        super.onStart()
        mFile ?: let {
            mFile = File(getExternalFilesDir(null), "simple.jpg")
        }
    }

}